﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Odbc;

namespace SupplyChainManagement
{
    /// <summary>
    /// Main form for viewing inventory details (aka raw items)
    /// </summary>
    public partial class InventoryForm : Form
    {
        MainForm main;
        public static string lastIndex;

        public InventoryForm()
        {
            InitializeComponent();
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
        }

        public InventoryForm(MainForm main)
        {
            this.main = main;
            InitializeComponent();
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            LoadDatabase();
        }

        public void LoadDatabase()
        {      
            OdbcConnection dbMySQL = new OdbcConnection(MainForm.strConnect);
            try
            {
                //open database
                dbMySQL.Open();

                OdbcCommand sqlCommand = dbMySQL.CreateCommand();
                //assign the SQL command
                sqlCommand.CommandText = "select * from inventory";

                //reader executes the select command
                OdbcDataReader sqlReader = sqlCommand.ExecuteReader();

                //clear the columns view
                dataGridView.Columns.Clear();
                DataGridViewColumn colHead;
                //apply default textbox columns style
                DataGridTextBoxColumn colStyle = new DataGridTextBoxColumn();
                //apply default cell style
                DataGridViewCell cell = new DataGridViewTextBoxCell();
                //num of column fields
                int dvgCount = sqlReader.FieldCount;
                int dvgStart = 0; //starting point
                while (dvgStart >= 0 && dvgStart < dvgCount)
                {
                    colHead = new DataGridViewColumn(); //create new column
                    colHead.Name = sqlReader.GetName(dvgStart); //get column name
                    colHead.CellTemplate = cell; //apply cell template
                    dataGridView.Columns.Add(colHead); //add column to the dgv 
                    dvgStart++;
                }
                //add the "amount" column
                colHead = new DataGridViewColumn();
                colHead.Name = "Amount";
                colHead.CellTemplate = cell;
                dataGridView.Columns.Add(colHead);

                dvgStart = 0;

                string[] holder = new string[dvgCount+1]; //query holder
                while (sqlReader.Read())
                {
                    while (dvgStart >= 0 && dvgStart < dvgCount)
                    {
                        holder[dvgStart] = sqlReader.GetString(dvgStart); //build row
                        lastIndex = sqlReader.GetString(0);
                        if (dvgStart == (dvgCount - 1))
                        {
                            //to manipulate the amount column
                            
                            OdbcCommand amountCmd = dbMySQL.CreateCommand();
                            amountCmd.CommandText = "select * from rawitem where inv_id='" +
                                sqlReader.GetString(0) + "'";
                            OdbcDataReader amtReader = amountCmd.ExecuteReader();
                            int inventoryAmt = 0;
                            while (amtReader.Read())
                            {
                                inventoryAmt++;
                            }
                            holder[dvgCount] = inventoryAmt.ToString();
                            //if last item, whole row  has been read, therefore add to dgv row
                            dataGridView.Rows.Add(holder);
                            amtReader.Close();
                            amountCmd.Dispose();
                        }
                        dvgStart++;
                    }
                    dvgStart = 0;
                }
                //close readers and dispose the commands                
                sqlReader.Close();
                sqlCommand.Dispose();
            }
            catch (OdbcException ex)
            {
                Console.WriteLine("Database error\n\n{0}", ex.ToString());
            }
            finally
            {
                if (dbMySQL != null) dbMySQL.Close();
            }
        }

        /// <summary>
        /// Pops up the add entry form and disable this form's control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Clicked(object sender, EventArgs e)
        {
            InventoryAddForm add = new InventoryAddForm(this);
            add.Show();
            this.Enabled = false;
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure?", "Delete entry", MessageBoxButtons.YesNo);
            //if user clicks yes
            if (result == DialogResult.Yes)
            {
                OdbcConnection dbMySQL = new OdbcConnection(MainForm.strConnect);
                try
                {
                    dbMySQL.Open();

                    OdbcCommand sqlCommand = dbMySQL.CreateCommand();
                    string toDel = (string)dataGridView.CurrentCell.Value; //get the cell that's gonna be deleted
                    sqlCommand.CommandText = "delete from inventory WHERE inv_id='" + toDel + "'";
                    sqlCommand.ExecuteNonQuery();
                    sqlCommand.Dispose();

                    OdbcCommand rawItemCmd = dbMySQL.CreateCommand();
                    rawItemCmd.CommandText = "delete from rawitem WHERE inv_id='" + toDel + "'";
                    rawItemCmd.ExecuteNonQuery();
                    rawItemCmd.Dispose();

                    MessageBox.Show("Success!");
                }
                catch (OdbcException ex)
                {
                    Console.WriteLine("Database error\n\n{0}", ex.ToString());
                }
                finally
                {
                    if (dbMySQL != null) dbMySQL.Close();
                    LoadDatabase();
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            string toEdit = (string)dataGridView.CurrentCell.Value;
            if (string.IsNullOrEmpty(toEdit))
                MessageBox.Show("No item selected.");
            else
            {
                System.Console.WriteLine(dataGridView.CurrentRow.Cells);
                InventoryEditForm edit = new InventoryEditForm(this, dataGridView.CurrentRow.Cells);
                edit.Show();
                this.Enabled = false;
            }
        }

        private void InventoryForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            main.Enabled = true;
            main.Activate();
        }

        private void btnDetail_Click(object sender, EventArgs e)
        {
            InventoryDetail inv = new InventoryDetail(this, dataGridView.CurrentCell.Value.ToString());
            this.Enabled = false;
            inv.Show();
        }

        private void btnOrder_Click(object sender, EventArgs e)
        {
            OrderInventory order = new OrderInventory(this);
            this.Enabled = false;
            order.Show();
        }
    }
}
